<?php

namespace app\admin\model;

use think\Model;

class Rule extends Model {

    protected $pk = 'id';

    function saveData($data,$action,$id = ''){
        if (empty($data['name'])){
            return ['code' => 'err', 'msg' => '名称不能为空'];
        }elseif ($data['pid'] == '' || $data['pid'] == null){
            return ['code' => 'err', 'msg' => '请选择上级'];
        }elseif ($data['pid'] != 0 && empty($data['rule'])){
            return ['code' => 'err', 'msg' => '请输入url'];
        }

        $data['is_menu'] = empty($data['is_menu']) ? 0 : 1;//是否菜单。1：是；0：否
        $data['status'] = empty($data['status']) ? 0 : 1;//状态。1：启用；0：停用
        $data['rule'] = $data['pid'] != 0 ? $data['rule'] : '';
        $data['update_time'] = time();
        if ($action == 'add'){
            $data['create_time'] = time();
        }
        $repeat = son_repeat('rule',$data['pid'],$data['name'],$id);
        if ($repeat){
            return ['code' => 'err', 'msg' => '当前权限下已存在' . $data['name']];
        }

        if ($action == 'add'){
            return $this->add($data);
        }elseif ($action == 'edit'){
            return $this->edit($id,$data);
        }
    }

    private function add($data){
        $result = self::allowField(true)->insertGetId($data);
        if ($result){
            insert_system_log('添加权限：' . $result);
            return ['code' => 'suc', 'msg' => '添加成功'];
        }else{
            return ['code' => 'err', 'msg' => '系统繁忙，请重试'];
        }
    }

    private function edit($id,$data){
        $result = self::allowField(true)->where('id',$id)->update($data);
        if ($result){
            insert_system_log('修改权限：' . $id);
            return ['code' => 'suc', 'msg' => '修改成功'];
        }else{
            return ['code' => 'err', 'msg' => '系统繁忙，请重试'];
        }
    }

    function delData($id){
        $son = self::where('pid',$id)->select();
        if (!empty($son)){
            $son_ids = [];
            foreach ($son as $v){
                array_push($son_ids,intval($v['id']));
            }
            array_push($son_ids,$id);
        }else{
            $son_ids[] = $id;
        }

        //开启事务
        db()->startTrans();
        try{
            db('rule')->where('id','in',$son_ids)->delete();
            db('role_rule')->where('rule_id','in',$son_ids)->delete();
            insert_system_log('删除权限：'. $id);
            //提交事务
            db()->commit();
            return ['code' => 'suc', 'msg' => '已删除'];
        }catch (\Exception $e){
            //事务回滚
            db()->rollback();
            return ['code' => 'err', 'msg' => '删除失败'];
        }
    }
}